//
//  PPMeUserInfoController.m
//  PropertyManage
//
//  Created by Dreamsoul on 15-3-25.
//  Copyright (c) 2015年 com.lab603.mc. All rights reserved.
//

#import "PPMeUserInfoController.h"
#import "PPMeEditBaseController.h"
#import "IWNavigationController.h"
#import "PPMeInfoSexController.h"
#import "PPMeInfoIconCellFrame.h"
#import "PPMeInfoTextCellFrame.h"
#import "PPMeInfoTextCell.h"
#import "PPMeInfoIconCell.h"
#import "AFNetWorking.h"
#import "PPMe.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
#import "EGOCache.h"
#import "UserInfo.h"
#import "PECropViewController.h"
#define Cache_UserInfoKey @"UserInfoCache"
#define CacheTime 24*60*60
@interface PPMeUserInfoController ()<UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,PECropViewControllerDelegate>
@property (nonatomic,strong)NSMutableArray *iconArray;
@property (nonatomic,strong)NSMutableArray *infoArray;
//本地保存的用户模型
@property (nonatomic,strong)UserInfo *userInfo;
@end

@implementation PPMeUserInfoController
/**
 *  用户模型的懒加载
 */
- (UserInfo *)userInfo{
    if (_userInfo==nil) {
        _userInfo = (UserInfo *)[[EGOCache globalCache] objectForKey:Cache_UserInfoKey];
    }
    return _userInfo;
}
- (NSMutableArray *)iconArray{
    if (_iconArray==nil) {
        _iconArray = [NSMutableArray array];
        PPMe *iconMe = [[PPMe alloc] init];
        //iconMe.userIcon = [defaults objectForKey:PPIcon];
        iconMe.icon = self.userInfo.icon;
        iconMe.titleString = @"头像";
        PPMeInfoIconCellFrame *iconMeF = [[PPMeInfoIconCellFrame alloc] init];
        iconMeF.me = iconMe;
        [_iconArray addObject:iconMeF];
        
    }
    return _iconArray;
}
- (NSMutableArray *)infoArray{
    if (_infoArray==nil) {
        _infoArray = [NSMutableArray array];
        //从本地存取的用户数据中拿取数据
        PPMe *infoMe1 = [[PPMe alloc] init];
        infoMe1.titleString = @"用户名";
        infoMe1.typeString = self.userInfo.name;
        PPMeInfoTextCellFrame *infoMe1F = [[PPMeInfoTextCellFrame alloc] init];
        infoMe1F.me = infoMe1;
        [_infoArray addObject:infoMe1F];
        //住址
        PPMe *infoMe2 = [[PPMe alloc] init];
        infoMe2.titleString = @"住址";
        infoMe2.typeString = self.userInfo.room;
        PPMeInfoTextCellFrame *infoMe2F = [[PPMeInfoTextCellFrame alloc] init];
        infoMe2F.me = infoMe2;
        [_infoArray addObject:infoMe2F];
        //职业
        PPMe *infoMe3 = [[PPMe alloc] init];
        infoMe3.titleString = @"职业";
        infoMe3.typeString = self.userInfo.job;
        PPMeInfoTextCellFrame *infoMe3F = [[PPMeInfoTextCellFrame alloc] init];
        infoMe3F.me = infoMe3;
        [_infoArray addObject:infoMe3F];
        //性别
        PPMe *infoMe4 = [[PPMe alloc] init];
        infoMe4.titleString = @"性别";
        infoMe4.typeString = self.userInfo.sex;
        PPMeInfoTextCellFrame *infoMe4F = [[PPMeInfoTextCellFrame alloc] init];
        infoMe4F.me = infoMe4;
        [_infoArray addObject:infoMe4F];
        //年龄
        PPMe *infoMe5 = [[PPMe alloc] init];
        infoMe5.titleString = @"年龄";
        infoMe5.typeString = self.userInfo.age;
        PPMeInfoTextCellFrame *infoMe5F = [[PPMeInfoTextCellFrame alloc] init];
        infoMe5F.me = infoMe5;
        [_infoArray addObject:infoMe5F];

    }
    return _infoArray;
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.title = @"个人信息";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = IWColor(239, 239, 239);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollEnabled = NO;

}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger number = 0;
    if (section==0) {
        number = self.iconArray.count;
    }else if (section==1){
        number = self.infoArray.count;
    }
    return number;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPMeInfoIconCell *cell = [PPMeInfoIconCell cellWithTableView:tableView];
    if (indexPath.section==0) {
        PPMeInfoIconCellFrame *iconCellF = self.iconArray[indexPath.row];
        cell.infoIconCellF = iconCellF;
    }else if(indexPath.section==1){
        PPMeInfoTextCell *textCell = [PPMeInfoTextCell cellWithTableView:tableView];
        PPMeInfoTextCellFrame *textCellF = self.infoArray[indexPath.row];
        textCell.infoTextCellF = textCellF;
        if (indexPath.row==0) {
            //若是用户名则设置为不可选中
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return textCell;
    }
    return  cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat cellHeight = 0;
    if (indexPath.section==0) {
        PPMeInfoIconCellFrame *userIconcellF = self.iconArray[indexPath.row];
        cellHeight = userIconcellF.cellHeight;
    }else if(indexPath.section==1){
        PPMeInfoTextCellFrame *textCellF = self.infoArray[indexPath.row];
        cellHeight = textCellF.cellHeight;
    }
    return cellHeight;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:@"拍照"
                                                        otherButtonTitles:@"用户相册", nil];
        [actionSheet showInView:self.view];
        //取消选中状态
        [tableView deselectRowAtIndexPath:indexPath animated:YES];

    }else if (indexPath.section==1){
        if (indexPath.row!=0&&indexPath.row!=3) {
            PPMeInfoTextCellFrame *infoF = self.infoArray[indexPath.row];
            PPMeEditBaseController *editVC = [[PPMeEditBaseController alloc] init];
            [editVC setUserInfoRefreshBlock:^(PPMe *me) {
                //更新用户信息
                [self refreshUserInfo:me];
            }];
            editVC.type = infoF.me.titleString;
            IWNavigationController *nav = [[IWNavigationController alloc]initWithRootViewController:editVC];
            [self presentViewController:nav animated:YES completion:nil];
        }else if (indexPath.row==3){
            PPMeInfoSexController *infoSexVC = [[PPMeInfoSexController alloc]init];
            [infoSexVC setUserSexRefreshBlock:^(UserInfo *userInfo) {
                //更新用户性别
                [self refreshUserSex:userInfo];
            }];
            [self.navigationController pushViewController:infoSexVC animated:YES];
        }
    }
}
/**
 *  更新用户性别
 */
- (void)refreshUserSex:(UserInfo *)userInfo{
    PPMeInfoTextCellFrame *infoF = self.infoArray[3];
    infoF.me.typeString = userInfo.sex;
    [self.infoArray replaceObjectAtIndex:3 withObject:infoF];
    //刷新表格数据
    [self.tableView reloadData];
}
/**
 *  更新用户信息
 */
- (void)refreshUserInfo:(PPMe *)me{
    int index = 0;
    if ([me.typeString isEqualToString:@"room"]) {
        index = 1;
    }else if([me.typeString isEqualToString:@"job"]){
        index = 2;
    }else if([me.typeString isEqualToString:@"age"]){
        index = 4;
    }
    PPMeInfoTextCellFrame *infoF = self.infoArray[index];
    PPMe *newMe = infoF.me;
    if ([me.typeString isEqualToString:@"age"]) {
        newMe.typeString = me.userInfo.age;
    }else if([me.typeString isEqualToString:@"room"]){
        newMe.typeString = me.userInfo.room;
    }else if ([me.typeString isEqualToString:@"job"]){
        newMe.typeString = me.userInfo.job;
    }
    infoF.me = newMe;
    [self.infoArray replaceObjectAtIndex:index withObject:infoF];
    //刷新表格数据
    [self.tableView reloadData];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSString *titile = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([titile isEqualToString:@"拍照"]) {
        [self openCamera];
    }else if([titile isEqualToString:@"用户相册"]){
        [self openPhotoLibrary];
    }
}
/**
 *  打开照相机
 */
- (void)openCamera{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}
/**
 *  打开相册
 */
- (void)openPhotoLibrary{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}
/**
 *  PEPhotoCrop的确定代理方法
 */
- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage{
    [self.navigationController popViewControllerAnimated:YES];
    [self updateUserPhoto:UIImageJPEGRepresentation(croppedImage, 0.4f) success:^{
        [MBProgressHUD showError:@"修改成功"];
    }];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // 1.销毁picker控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 2.取得图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    //3.截图
    PECropViewController *controller = [[PECropViewController alloc] init];
    controller.delegate = self;
    controller.image = image;
    controller.title = @"裁剪";
    controller.toolbarHidden = YES;
    [self.navigationController pushViewController:controller animated:YES];
    }
/**
 *  PEPhotoCrop的取消代理方法
 */
- (void)cropViewControllerDidCancel:(PECropViewController *)controller{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  对获得的图像数据进行处理
 */
- (void)updateUserPhoto:(NSData *)imgData success:(void(^)())success{
    //上传图片数据
    NSString *urlString = [NSString stringWithFormat:@"%@/%@",BaseUrl,@"user/edit"];
    // AFNetworking\AFN
    // 1.创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // 说明服务器返回的JSON数据
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    //2.封装请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"userId"] = self.userInfo.ID;
    //上传数据
    [mgr POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { // 在发送请求之前调用这个block
        // 必须在这里说明要上传哪些文件
        [formData appendPartWithFileData:imgData name:@"icon" fileName:@"" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"resultCode"] intValue]==1) {
            //向服务器请求用户数据（主要是为了更新用户图像的url）
            NSString *userInfoUrl = [NSString stringWithFormat:@"%@/%@",BaseUrl,@"user/me"];
            NSMutableDictionary *UserInfoparams = [NSMutableDictionary dictionary];
            [mgr GET:userInfoUrl parameters:UserInfoparams success:^(AFHTTPRequestOperation *operation, id responseObject) {
                UserInfo *userInfo = [UserInfo objectWithKeyValues:responseObject];
                //对数据进行保存
                self.userInfo.icon = userInfo.icon;
                [[EGOCache globalCache] setObject:userInfo forKey:Cache_UserInfoKey withTimeoutInterval:CacheTime];
                //修改模型数据
                PPMeInfoIconCellFrame *iconF = [self.iconArray lastObject];
                iconF.me.icon = userInfo.icon;
                [self.iconArray removeAllObjects];
                [self.iconArray addObject:iconF];
                [self.tableView reloadData];
                //[MBProgressHUD showSuccess:@"修改成功"];
                if (self.userIconRefreshBlock) {
                    self.userIconRefreshBlock(userInfo);
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                IWLog(@"请求失败");
            }];
        }else{
            [MBProgressHUD showError:@"修改失败"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:@"修改失败"];
    }];

}
@end
